package com.yuan.schedule.fetch;

import java.util.Comparator;
import java.util.List;

import org.apache.log4j.Logger;

import com.taobao.pamirs.schedule.IScheduleTaskDealSingle;
import com.taobao.pamirs.schedule.TBScheduleManagerFactory;
import com.yuan.fetch.AutoFetch;
import com.yuan.service.autofetch.AutoFetchService;
import com.yuan.service.autofetch.impl.AutoFetchServiceImpl;

/**
 * 分布式调度，抓取文件
 * 
 * @author Beni
 * 
 */
public class AutoFetchSchedule implements IScheduleTaskDealSingle<AutoFetch> {

	private static Logger logger = Logger.getLogger(AutoFetchServiceImpl.class);

	private AutoFetchService autoFetchService;

	protected String taskType;

	protected String ownSign;
	
	public List<AutoFetch> selectTasks(String ownSign, int queueNum, List<String> queryCondition, int fetchNum) {

		StringBuffer condition = new StringBuffer();
		for (int i = 0; i < queryCondition.size(); i++) {
			if (i > 0) {
				condition.append(",");
			}
			condition.append(queryCondition.get(i));
		}

		List<AutoFetch> autoFetchs=autoFetchService.readNeedFetch(ownSign, fetchNum, queueNum, condition.toString());
		
		StringBuilder sb=new StringBuilder("线程："+Thread.currentThread());
		sb.append(Thread.currentThread());
		sb.append(",选择任务：");
		
		for (AutoFetch autoFetch : autoFetchs) {
			sb.append("\r\n");
			sb.append(autoFetch.getFetchUrl());
		}
		
		logger.info(sb.toString() );
		
		return autoFetchs;
	}

	public boolean execute(AutoFetch autoFetch, String ownSign) {
		try {
			
			autoFetchService.runFetch(autoFetch);
			logger.info("成功运行任务:"+autoFetch.getFetchUrl()+",线程"+Thread.currentThread());
			return true;
		} catch (Exception ex) {
			logger.error("运行任务失败:"+autoFetch.getFetchUrl()+",线程"+Thread.currentThread(),ex);
			return false;
		}
	}

	public Comparator<AutoFetch> getComparator() {

		return new Comparator<AutoFetch>() {
			public int compare(AutoFetch o1, AutoFetch o2) {
				return o1.getId().compareTo(o2.getId());
			}
		};
	}
	
	public void init() throws Exception {
		TBScheduleManagerFactory.createTBScheduleManager(taskType, ownSign);
	}

	public AutoFetchService getAutoFetchService() {
		return autoFetchService;
	}

	public void setAutoFetchService(AutoFetchService autoFetchService) {
		this.autoFetchService = autoFetchService;
	}

	public String getTaskType() {
		return taskType;
	}

	public void setTaskType(String taskType) {
		this.taskType = taskType;
	}

	public String getOwnSign() {
		return ownSign;
	}

	public void setOwnSign(String ownSign) {
		this.ownSign = ownSign;
	}

	public void nextScheduleSelectTasksInit(String arg0, int arg1, List<String> arg2) throws Exception {
		autoFetchService.toInitStatus();
	}
	
	
}
